import rea from './rea'
let ip = "www.robbeykaaso.work:3000"
//let ip = "localhost:3000"
let server = "https://" + ip
let ws_server = "wss://" + ip

//https://zhuanlan.zhihu.com/p/200805837
function request(options) {
  return new Promise((resolve, reject) => {
    // 逻辑：发送请求到服务器
    //console.log(options.data)
    wx.request({
      url: server + "/" + options.api,
      method: options.method || "GET",
      data:  options.data || {},
      header: options.header || {'Content-Type': 'application/json;charset=UTF-8'},
      success: res => {
        resolve(res)
      },
      fail: err => {
        reject(err)
      }
    })
  })
}

function login(){
  return new Promise((resolve, reject) => {
    wx.login({
      success: res => {
          resolve(res)
      },
      fail: err => {
        reject(err)
      }
    })
  })
}

function random(aStart, aEnd) {
  return Math.floor(Math.random() * (aEnd - aStart) + aStart)
}

let socketOpen = false
let socketMsgQueue = []

rea.pipelines().add(aInput => {
  aInput.out()
}, {name: "socketStatusChanged"})
.nextF(aInput => {
  if (!aInput.data())
    wx.connectSocket({
      url: ws_server
    })
})

wx.onSocketMessage((res) => {
  let dt = JSON.parse(res.data)
  rea.pipelines().run("fromServer", dt)
})

wx.onSocketOpen(function(res) {
  socketOpen = true
  rea.pipelines().run("socketStatusChanged", socketOpen)
  for (let i = 0; i < socketMsgQueue.length; i++){
    request2(socketMsgQueue[i])
  }
  socketMsgQueue = []
})

wx.onSocketClose((result) => {
  socketOpen = false
  rea.pipelines().run("socketStatusChanged", socketOpen)
})

wx.onSocketError((result) => {
  socketOpen = false
  rea.pipelines().run("socketStatusChanged", socketOpen)
})

function request2(msg) {
  if (socketOpen) {
    wx.sendSocketMessage({data: JSON.stringify(msg)})
  } else {
    socketMsgQueue.push(msg)
  }
}

module.exports = {
  request2,
  request,
  login,
  random
}